package com.xonro.common.histrans.util;


import com.actionsoft.bpms.bo.engine.BO;
import com.actionsoft.bpms.commons.database.RowMap;
import com.actionsoft.bpms.commons.formfile.model.FormFileModel;
import com.actionsoft.sdk.local.SDK;
import com.actionsoft.sdk.local.api.LogAPI;
import com.actionsoft.sdk.local.api.Logger;
import com.xonro.common.histrans.base.consts.DrpConst;
import com.xonro.common.histrans.sfeg.biz.CommTransBiz;
import jodd.util.StringUtil;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @Author:caipw
 * @Description:
 * @Date 2018/12/27
 */

public class FileHelper {
    private static Logger logger = LogAPI.getLogger(FileHelper.class);
    /**
     * 从网络Url中下载文件
     * @param urlStr
     * @throws IOException
     */
    public static HttpURLConnection downLoadFromUrl(String urlStr, String info){
        HttpURLConnection conn = null;
        if (isConnect(urlStr,"")){
            try {
                URL url = new URL(urlStr);
                conn = (HttpURLConnection)url.openConnection();

                //设置超时间为3秒
                conn.setConnectTimeout(3*1000);
                //防止屏蔽程序抓取而返回403错误
                conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
                //得到输入流
                InputStream inputStream = conn.getInputStream();
//        //获取自己数组
//        byte[] getData = readInputStream(inputStream);
//        //文件保存位置
//        File saveDir = new File(savePath);
//        if(!saveDir.exists()){
//            saveDir.mkdir();
//        }
//        File file = new File(saveDir+File.separator+fileName);
//        FileOutputStream fos = new FileOutputStream(file);
//        fos.write(getData);
//        if(fos!=null){
//            fos.close();
//        }
//        if(inputStream!=null){
//            inputStream.close();
//        }
//            System.out.println("info:"+info+"url:"+url+" download success");
            } catch (IOException e) {
                e.printStackTrace();
                logger.error(e.getMessage(),e);
            }
        }else{
            System.out.println("url:"+urlStr+" download failed");
        }
        return conn;
    }



    /**
     * 从网络Url中下载文件
     * @param urlStr
     * @throws IOException
     */
    public static HttpURLConnection Drp2Download(String urlStr,String token){
        HttpURLConnection conn = null;
        if (isConnect(urlStr,token)){
            try {
                URL url = new URL(urlStr);
                conn = (HttpURLConnection)url.openConnection();

                //设置超时间为3秒
                conn.setConnectTimeout(3*1000);
                //防止屏蔽程序抓取而返回403错误
                conn.setRequestMethod("GET");
                conn.setRequestProperty("F2bpmtoken",token);
                conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
                //得到输入流
                InputStream inputStream = conn.getInputStream();
//        //获取自己数组
//        byte[] getData = readInputStream(inputStream);
//        //文件保存位置
//        File saveDir = new File(savePath);
//        if(!saveDir.exists()){
//            saveDir.mkdir();
//        }
//        File file = new File(saveDir+File.separator+fileName);
//        FileOutputStream fos = new FileOutputStream(file);
//        fos.write(getData);
//        if(fos!=null){
//            fos.close();
//        }
//        if(inputStream!=null){
//            inputStream.close();
//        }
//            System.out.println("info:"+info+"url:"+url+" download success");
            } catch (IOException e) {
                e.printStackTrace();
                logger.error(e.getMessage(),e);
            }
        }else{
            System.out.println("url:"+urlStr+" download failed");
        }
        return conn;
    }

    /**
     * 功能：检测当前URL是否可连接或是否有效,
     * @param urlStr 指定URL网络地址
     * @return URL
     */
    public static synchronized boolean isConnect(String urlStr,String token) {
        URL url;
        HttpURLConnection con;
        int state = -1;
        int counts = 0;
        boolean isOk = false;
        if (urlStr == null || urlStr.length() <= 0) {
            isOk=false;
        }
        try {
            url = new URL(urlStr);

            con = (HttpURLConnection) url.openConnection();
            con.setRequestMethod("GET");
            con.setRequestProperty("F2bpmtoken","eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE3MDAxOTE3MjMsImF1dGhvckpzb24iOiJ7XCJ0aW1lU3RhbXBcIjpcIjE3MDAxOTE3MjMzMTVcIixcImxvZ2luT3JnSWRcIjpcIjAwXCIsXCJjb3JwSWRcIjpcIkFwcERlZmF1bHRcIixcInNpZ25hdHVyZVwiOlwiNVJZbzFGRUZ6SVF6c0pIb2JsMjhCZjhKdVJpNWhqYUN2dmljdkhjWmwzV2kwM2xKamVYVzJxb1hiNnZIdWdhQVJGV20zZU5qNG0xUyUwQTFvbXZ5NVhTdUgwOVd1RnlDaDVEXCIsXCJ0ZW5hbnRJZFwiOlwiQlBNXCIsXCJsb2dpblVzZXJJZFwiOlwiM2MxZGYwYjMtYTRkOS00NzMxLWIxNDMtMDJlODFiY2UxN2NlXCIsXCJub25jZVwiOlwiNTQ2MlwifSIsImlhdCI6MTcwMDEwNTMyM30.TePxhXDb_9AaMvNQcdbf3DsCmLDhDwTZfUTuhzZPR5E");
            state = con.getResponseCode();
            if (state == HttpURLConnection.HTTP_OK) {
                isOk=true;
            }
        } catch (Exception e) {
            e.printStackTrace();
            isOk=false;
        }
        return isOk;
    }

    /**
     * 从输入流中获取字节数组
     * @param inputStream
     * @return
     * @throws IOException
     */
    public static  byte[] readInputStream(InputStream inputStream) throws IOException {
        byte[] buffer = new byte[1024];
        int len = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while((len = inputStream.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
        bos.close();
        return bos.toByteArray();
    }

    /**
     * 上传文件至bpm
     * @param fkCode 单据编号
     * @throws IOException
     */
    public static void uploadToBpm(String fkCode, String boName, String boId, String fieldName, String processInstId ) throws IOException {
        List<RowMap> fileMaps = SDK.getCCAPI().getRDSAPI(DrpConst.ZZ_CCID).getMaps("SELECT * FROM tb_File WHERE fkCode = ?", fkCode);
        for(RowMap fileMap: fileMaps) {
            FormFileModel formFileModel = new FormFileModel();
            formFileModel.setBoName(boName);
            formFileModel.setBoId(boId);
            formFileModel.setFileName(fileMap.getString("FileName"));
            formFileModel.setBoItemName(fieldName);
            formFileModel.setProcessInstId(processInstId);
            formFileModel.setCreateUser(CommTransBiz.getInstance().getUserId(fileMap.getString("FileUser")));
            formFileModel.setCreateDate(fileMap.getTimestamp("FileDate"));
            String fileName = fileMap.getString("FileName");
            //格式化文件名为UTF-8
             String urlStr = "http://192.168.123.232/JCZGSFILES/" + URLEncoder.encode(fileMap.getString("FilePath") + fileMap.getString("FileNameID"), "utf-8");
            if (fileName.contains(".dwg")) {
                System.err.println(urlStr + "格式dwg");
            }
            HttpURLConnection conn = FileHelper.downLoadFromUrl( urlStr, boId);
            if (conn != null) {
                formFileModel.setFileSize(conn.getContentLengthLong());
                FileHelper.upFile(formFileModel, conn.getInputStream());
            }
        }
    }

    public static void uploadToBpmSplit(List<String> files, RowMap records, String subBoName, BO newBo, boolean isUpdate, String info) throws IOException {
        if (files.size()!=0){
            for (String file: files){
                String SMFile=records.getString("FILENAME");
                System.err.println(SMFile+"文件名");
                //获取附件名称
                String fileName = records.getString(file+"_FILENAME");
                System.err.println(fileName+"文件名");
                //获取附件路径
                String filePath = records.getString(file+"_FILEPATH");
                //获取附件创建人
                String fileCreateUser="";
                if (records.containsKey(file+"_UPER")){
                    fileCreateUser = records.getString(file+"_UPER");
                }
                //获取附件创建日期
                String fileCreateDate="";
                if (records.containsKey(file+"_UPDATE")){
                    fileCreateDate = records.getString(file+"_UPDATE");
                }



                //有附件
                if (StringUtil.isNotEmpty(fileName) && StringUtil.isNotEmpty(filePath) ){
                    if (isUpdate) {
                        SDK.getBOAPI().removeFiles(newBo.getId(),file);
                    }
                    String[] fileNames = fileName.replace("&amp;","&").split(";");
                    String[] filePaths = filePath.split(";");
                    String[] fileCreateUsers = fileCreateUser.split(";");
                    String[] fileCreateDates = fileCreateDate.split(";");
                    for(int i=0;i<fileNames.length;i++){
                        FormFileModel formFileModel = new FormFileModel();
                        formFileModel.setBoName(subBoName);
                        formFileModel.setBoId(newBo.getId());
                        formFileModel.setFileName(fileNames[i]);
                        formFileModel.setBoItemName(file);
                        formFileModel.setProcessInstId(newBo.getBindId());
                        formFileModel.setCreateUser("admin");
                        if (records.containsKey(file+"_UPER") && !";".equals(fileCreateUser)){
                            formFileModel.setExt1(fileCreateUsers[i]);
                        }
                        if (records.containsKey(file+"_UPDATE")){
                            formFileModel.setCreateDate(new Timestamp(dateToStamp(fileCreateDates[i])));
                        }
                        //格式化文件名为UTF-8
                        String enFilePath = filePaths[i].substring(filePaths[i].indexOf("/", 1) + 1);
                        String urlStr = filePaths[i].substring(0,filePaths[i] .indexOf("/", 1))+"/"+URLEncoder.encode(enFilePath,"utf-8");
                        HttpURLConnection conn = FileHelper.downLoadFromUrl("http://" + urlStr,info);
                        if (conn!=null){
                            formFileModel.setFileSize(conn.getContentLengthLong());
                            FileHelper.upFile(formFileModel,conn.getInputStream());
                        }
                    }
                }
            }
        }
    }


    public static void upFile(FormFileModel formFileModel, InputStream inputStream) {
        try {
           // formFileModel.setAppId("com.xonro.apps.mdm");
            SDK.getBOAPI().upFile(formFileModel,inputStream);
        } catch (Exception e){
            logger.error(e.getMessage(),e);
            e.printStackTrace();
        } finally {
            try {
                if(inputStream!=null){
                    inputStream.close();
                }
            } catch (Exception e) {
                logger.error(e.getMessage(),e);
                e.printStackTrace();
            }
        }


    }

    /**
     * 将时间转换为时间戳
     */
    public static long dateToStamp(String s){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = null;
        try {
            date = simpleDateFormat.parse(s);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        long ts = 0;
        if (date != null) {
            ts = date.getTime();
        }
        return ts;
    }

    public static void main(String[] args) {
//        String s= "_timestamp=1540365767&clientId=25405789376086016&clientSecret=EB027481EB1711E7845302A6E03210C4&idCard=432302197609096333";
//        byte[] b = DigestUtils.md5Digest(s.getBytes());
//        //在对md5后的字节流进行hex编码
//        String str = "";
//        for (int i = 0; i < b.length; i++)
//        {
//            str += String.format("{0:X2}", b[i]);
//        }
//        String strsignature = str.toLowerCase();
//        System.err.println(strsignature);
//        System.err.println(DigestUtils.md5DigestAsHex(s.getBytes()));
        String[] fileNames = "（新）基地防火管理规定.doc".replace("&amp;","&").split(";");
        String[] fileCreateUsers = "危险品专项整治活动通知（顾）.doc;危险品专项整治活动通知（顾）.doc;附件1-拟收购上海地铁盾构30%股权的预报告.doc;附件1-拟收购上海地铁盾构30%股权的预报告.doc;附件1-拟收购上海地铁盾构30%股权的预报告.doc;附件1-拟收购上海地铁盾构30%股权的预报告.doc;附件2-上海建工集团股份有限公司抄告单（沪建集股{投资}抄字2014-09）.doc;附件3-三方协议.pdf;附件4-基础集团拟参股投资的盾构设备清单及初步评估值表.xls;附件5-基础集团《关于拟参股上海地铁盾构设备工程有限公司股权的决议》.doc;上海建工集团股份有限公司印发《关于加强企业工资总额管理的暂行规定》的通知.doc;关于加强企业工资总额管理的暂行规定（修改稿）.doc;上海建工集团股份有限公司关于执行《在本市建筑工程施工现场推行作业人员实名制管理的通知》的工作方案.doc;职工电子身份信息卡(IC卡)办理办法.doc;沪建安质监[2014]82号.pdf;2号文《关于钱美刚和李呈旸同志的任职的决定》.pdf;2015年上海市基础工程集团有限公司培训开班汇总表.xls;荷兰Invitation letter.pdf;SAOBD_15061209440.pdf;荷兰Invitation letter.pdf;关于拟投资设立上海康益海洋工程有限公司的请示.docx;抄告单.doc;上海市基础工程集团有限公司董事会决议.doc;章程（金改后20151102）.doc;文件通知.doc;项目效益真实性、合规性审计检查实施办法.doc;消防安全责任约谈管理办法.doc;附件1上海市基础工程集团有限公司2016年度合格供方（厂、商）名录和附件2上海建工集团股份有限公司厂商准入名录.doc;1.png;（2）公推直选方案.doc;《2016年上半年项目效益真实性、管理合规性审计报告》整改报告.doc;1.txt;管理型项目商务策划附表(临港一期新建项目A1地块项目（2017.11.1送).xlsx;临港新建项目商务策划书10.30.docx".split(";");
        System.err.println(fileCreateUsers.length);



    }

}
